<template>
  <div class="attendance_result_report">

    <div class="tool">
      <div class="select">
        <el-form :inline="true" size="small">
          <el-form-item>
            <ToolBar :update-disable="multipleSelection.length!==1" :update-data="updateById" :show-all="true"
                     :delete-disable="multipleSelection.length===0" :delete-data="deleteById"
                     :add-data="setAddDialogVisible" :show-multiple="false" :add-batch-data="addBatchData"></ToolBar>
          </el-form-item>
          <el-form-item label="部门：">
            <el-select v-model="form.depts" multiple placeholder="请选择部门..." @change="deptChange" size="small"
                       filterable clearable>
              <el-option :label="item.deptLevel2" :value="item.deptLevel2" v-for="item in deptList">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="组别：">
            <el-select v-model="form.groupNames" multiple placeholder="请选择组别..." size="small"
                       filterable clearable>
              <el-option :label="item.groupName" :value="item.groupName" v-for="item in groupList">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名：">
            <el-select v-model="form.userIds" placeholder="请选择员工姓名..." value-key="userId" size="small" multiple :collapse-tags="true" style="width: 20vw;"
                       filterable clearable>
              <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.userId" v-for="item in $store.state.userList">
                <span style="float: left">{{ item.userName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
              </el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="工号：">-->
<!--            <el-select v-model="form.jobNos" placeholder="请选择员工工号..." value-key="jobNo" size="small" multiple :collapse-tags="true" style="width: 20vw;"-->
<!--                       filterable clearable>-->
<!--              <el-option :label="item.jobNo+'('+item.userName+')'" :value="item.jobNo" v-for="item in $store.state.userList">-->
<!--                <span style="float: left">{{ item.jobNo }}</span>-->
<!--                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.userName }}</span>-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="排班：">
            <el-select v-model="form.salaryrosteringtypes" multiple >
              <el-option value="正班"></el-option>
              <el-option value="休息"></el-option>
              <el-option value="周末"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="出勤情况：">
            <el-select v-model="form.type" placeholder="请选择..." value-key="userId" @change="handleCurrentChange(1)"
                       size="small"
                       filterable clearable>
              <el-option label="正常" value="normal"></el-option>
              <el-option label="不正常" value="abnormal"></el-option>
              <el-option label="公休" value="gx"></el-option>
              <el-option label="全部" value=""></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期：">
            <el-date-picker size="small"
                            @change="dateChange"
                            v-model="attendanceDate"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            align="left"
                            :picker-options="pickerOptions"
                            :clearable="false"
            >
            </el-date-picker>
          </el-form-item>




          <el-form-item>
            <el-button type="primary" @click="goGetData" size="small">考勤计算</el-button>
            <el-button type="primary" @click="exportData(false)" size="small">导出本页</el-button>
            <el-button type="primary" @click="exportData(true)" size="small">导出全部</el-button>
            <el-button type="primary" @click="sjhd" size="small">数据核对</el-button>
              <el-button type="primary" @click="reSet" size="small" icon="el-icon-refresh">重置
              </el-button>
            <el-button type="primary" @click="handleCurrentChange(1)" size="small" style="width: 10rem;">筛 选</el-button>

          </el-form-item>


        </el-form>
      </div>
      <el-dialog title="考勤计算" :visible.sync="getDataDialogFormVisible" center width="35%">
        <el-row>
          <el-form :model="form" label-width="3rem">
            <el-form-item label="姓名:">
              <el-select v-model="form.userIds" placeholder="请选择员工姓名..." value-key="userId" size="small" class="w100" multiple :collapse-tags="true" style="width: 20vw;"
                         @change="handleUserChange"
                         filterable clearable>
                <el-option :label="item.userName+'（'+item.jobNo+'）'" :value="item.userId" v-for="item in $store.state.userList">
                  <span style="float: left">{{ item.userName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.jobNo }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期:">
              <el-date-picker  v-model="attendanceDate" size="small"
                               type="daterange"
                               style="width: 100%"
                               align="left"
                               unlink-panels
                               range-separator="至"
                               start-placeholder="开始日期"
                               end-placeholder="结束日期"
                               :default-time="['00:00:00', '23:59:59']"
                               :picker-options="pickerOptions"
                               :clearable="false"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="getDataDialogFormVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="getDataFromDingDing">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="数据核对" :visible.sync="sjhdDialogFormVisible" center width="60%">
        <el-row>
          <el-form :model="sjhdForm" label-width="3rem" ref="sjhdForm">
            <el-form-item label="日期:" prop="attendanceDate" :rules="{
      required: true, message: '请先选择日期', trigger: 'blur'}" label-width="15%">
              <el-date-picker  v-model="sjhdForm.attendanceDate" size="small"
                               type="daterange"
                               style="width: 85%"
                               align="left"
                               unlink-panels
                               range-separator="至"
                               start-placeholder="开始日期"
                               end-placeholder="结束日期"
                               :default-time="['00:00:00', '23:59:59']"
                               :picker-options="pickerOptions"
                               :clearable="false"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item prop="fileList" :rules="{
      required: true, message: '请上传文件', trigger: 'blur'}">
              <el-upload
                  class="upload-demo"
                  ref="upload"
                  :http-request="sjhdReport"
                  :on-change="handleChangeUpload"
                  :limit="1"
                  action="#"
                  :data="sjhdForm">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">注意：上传文件的考勤时间区间应与上面选择的日期区间一致！</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-row>
        <el-table height="450"
            :data="errorData"
            stripe
            border
            :header-cell-style="{'text-align':'center'}"
            :cell-style="{'text-align':'center'}">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table
                  :data="props.row.result"
                  stripe
                  border
                  default-expand-all
                  :header-cell-style="{'text-align':'center'}"
                  :cell-style="{'text-align':'center'}">
                <el-table-column label="工作日期" min-width="120">
                  <template slot-scope="scope">
                    {{ scope.row.workDate|formatDateBirth }}
                  </template>
                </el-table-column>
                <el-table-column label="基本出勤（excel）" min-width="150">
                  <template slot-scope="scope">
                    {{ scope.row.excelData.jbcq}}
                  </template>
                </el-table-column>
                <el-table-column label="基本出勤" min-width="120">
                  <template slot-scope="scope">
                    {{ scope.row.report.basicattendance}}
                  </template>
                </el-table-column>
                <el-table-column label="基本加班（excel）" min-width="150">
                  <template slot-scope="scope">
                    {{ scope.row.excelData.jbjb}}
                  </template>
                </el-table-column>
                <el-table-column label="基本加班" min-width="120">
                  <template slot-scope="scope">
                    {{ scope.row.report.basicovertime}}
                  </template>
                </el-table-column>
                <el-table-column label="超时加班（excel）" min-width="150">
                  <template slot-scope="scope">
                    {{ scope.row.excelData.csjb}}
                  </template>
                </el-table-column>
                <el-table-column label="超时加班" min-width="120">
                  <template slot-scope="scope">
                    {{ scope.row.report.overtime}}
                  </template>
                </el-table-column>
                <el-table-column label="总时长（excel）" min-width="120">
                  <template slot-scope="scope">
                    {{ scope.row.excelData.zsc}}
                  </template>
                </el-table-column>
                <el-table-column label="总时长" min-width="120">
                  <template slot-scope="scope">
                    {{ scope.row.report.totalduration}}
                  </template>
                </el-table-column>
                <el-table-column label="连班加班" min-width="120">
                  <template slot-scope="scope">
                    {{ scope.row.report.continuousshifthours}}
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column label="excel序号" prop="xh">
          </el-table-column>
          <el-table-column label="姓名" prop="name">
          </el-table-column>
          <el-table-column label="工号" prop="jobNo">
          </el-table-column>
          <el-table-column label="部门" prop="dept">
          </el-table-column>
        </el-table>
      </el-dialog>

    </div>
    <el-table
        id="table-detail"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column label="员工姓名" prop="fullname" width="100" fixed>
        <template slot-scope="scope">
          <span @click="getDingAttendanceDetail(scope.row)"> {{ scope.row.fullname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="员工工号" prop="jobno" width="100" fixed>
      </el-table-column>
      <el-table-column label="职位" prop="position" width="100" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="所在部门" prop="dept" :show-overflow-tooltip="true" min-width="100">
      </el-table-column>
      <el-table-column label="上班日期" prop="attendancedate" min-width="120">
        <template slot-scope="scope" v-if="scope.row.attendancedate">
          {{ scope.row.attendancedate|formatDateBirth }}
        </template>
      </el-table-column>
      <el-table-column label="星期" prop="week">
      </el-table-column>
      、<el-table-column label="薪资排班" prop="salaryrosteringtype" width="120">
      </el-table-column>
      <el-table-column label="白夜班" prop="shift" width="100">
      </el-table-column>
      <el-table-column label="基本出勤" prop="basicattendance" width="100">
      </el-table-column>
      <el-table-column label="连班加班" prop="continuousshifthours" width="100">
      </el-table-column>
      <el-table-column label="基本加班" prop="basicovertime" width="100">
      </el-table-column>
      <el-table-column label="超时加班" prop="overtime" width="100">
      </el-table-column>
      <el-table-column label="总出勤" prop="totalduration" width="80">
      </el-table-column>
      <el-table-column label="上班打卡时间" prop="onDuty" width="170">
        <template slot-scope="scope" v-if="scope.row.onDuty">
          {{ scope.row.onDuty|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="下班打卡时间" prop="offDuty" width="170">
        <template slot-scope="scope" v-if="scope.row.offDuty">
          {{ scope.row.offDuty|formatDate }}
        </template>
      </el-table-column>

      <el-table-column label="组别" prop="groupName" show-overflow-tooltip>
      </el-table-column>

      <el-table-column label="备注" prop="summary" :show-overflow-tooltip="true" fixed="right">
        <template slot-scope="scope">
          <span @click="getDingAttendanceDetail(scope.row)"> {{ scope.row.summary }}</span>
        </template>
      </el-table-column>
      <el-table-column label="迟早旷" prop="summary" :show-overflow-tooltip="true"  fixed="right">
        <template slot-scope="scope">
          <span v-if="scope.row.late">迟到</span>
          <span v-if="scope.row.early">早退</span>
          <span v-if="scope.row.absenteeisms">旷工</span>
        </template>
      </el-table-column>
      <el-table-column label="手动调整" prop="summary"  fixed="right" min-width="100">
        <template slot-scope="scope" >
          <el-tag type="waring" v-show="scope.row.fixed">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计算时间" :show-overflow-tooltip="true" width="100">
        <template slot-scope="scope">
          {{ scope.row.createtime|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150">
        <template slot-scope="scope" v-show="!isDowload">
          <el-button
              size="mini"
              @click="handleEdit(scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          hide-on-single-page
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[size, size*2, size*3, size*4,total]"
          :page-size=size
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <el-drawer
        title="打卡数据"
        :visible.sync="drawer"
        :direction="direction">
      <div slot="title">
        <h2><span>{{ row.fullname }}打卡数据</span><span
            class="float-end">（{{ row.attendancedate|formatDateBirth }}）</span></h2>
      </div>
      <div style="margin-left: 2rem">
        <el-descriptions :title="'打卡类型:'+item.checkType" v-for="item in attendanceResultList" column=1
                         :key="item.id">
          <el-descriptions-item label="标准打卡时间">{{ item.baseCheckTime|formatDate }}</el-descriptions-item>
          <el-descriptions-item label="实际打卡时间">{{ item.userCheckTime|formatDate }}</el-descriptions-item>
          <el-descriptions-item label="数据来源">{{ item.sourceType }}</el-descriptions-item>
          <el-descriptions-item label="打卡结果">{{ item.timeResult }}</el-descriptions-item>
          <el-descriptions-item label="审批单"><span @click="getApprove(item)">{{ item.procinstId }}</span>
          </el-descriptions-item>
        </el-descriptions>
        备注：
        <el-tag type="danger" v-text="row.summary"></el-tag>
        <el-drawer
            title="审批单详情"
            :append-to-body="true"
            :before-close="handleClose"
            :visible.sync="innerDrawer">
          <div slot="title">
            <h2>审批单详情</h2>
          </div>
          <div style="margin-left: 2rem">
            <el-descriptions :title="'审批单名称:'+approve.tagName+''+approve.subType" column=1 v-if="approve!=null">
              <el-descriptions-item label="姓名">{{ approve.userName }}</el-descriptions-item>
              <el-descriptions-item label="工号">{{ approve.jobNo }}</el-descriptions-item>
              <el-descriptions-item label="时长">{{ approve.duration }}</el-descriptions-item>
              <el-descriptions-item label="时长单位">{{ approve.durationUnit }}</el-descriptions-item>
              <el-descriptions-item label="开始时间">{{ approve.beginTime|formatDate }}</el-descriptions-item>
              <el-descriptions-item label="结束时间">{{ approve.endTime|formatDate }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </el-drawer>
      </div>

    </el-drawer>
    <el-drawer :title="'考勤结果'+(isAdd?'添加':'修改')"
               :visible="drawer1"
               :before-close="handleClose"
               :direction="direction">
      <el-row style="padding:0 1rem 0 2rem">
        <el-form :model="attendanceResultReport" label-position="left" :rules="rules" ref="attendance">
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="fullname">
            <el-input v-model="attendanceResultReport.fullname" :disabled="!isAdd"></el-input>
          </el-form-item>
          <el-form-item label="工号" :label-width="formLabelWidth" prop="jobno">
            <el-input v-model="attendanceResultReport.jobno" :disabled="!isAdd"></el-input>
          </el-form-item>
          <el-form-item label="出勤日期" :label-width="formLabelWidth" prop="attendancedate">
            <el-date-picker v-model="attendanceResultReport.attendancedate" class="w100"
                            :disabled="!isAdd"></el-date-picker>
          </el-form-item>
          <el-form-item label="上班打卡" :label-width="formLabelWidth" prop="onDuty">
            <el-date-picker disabled v-model="attendanceResultReport.onDuty"></el-date-picker>
            <el-time-picker disabled v-model="attendanceResultReport.onDuty"></el-time-picker>
          </el-form-item>
          <el-form-item label="下班打卡" :label-width="formLabelWidth" prop="offDuty" >
            <el-date-picker disabled v-model="attendanceResultReport.offDuty"></el-date-picker>
            <el-time-picker disabled v-model="attendanceResultReport.offDuty"></el-time-picker>
          </el-form-item>
          <el-form-item label="基本出勤" :label-width="formLabelWidth" prop="basicattendance">
            <el-input disabled v-model="attendanceResultReport.basicattendance" @change="numberChange" type="number"></el-input>
          </el-form-item>
          <el-form-item label="基本加班" :label-width="formLabelWidth" prop="basicovertime">
            <el-input disabled v-model="attendanceResultReport.basicovertime" @change="numberChange"></el-input>
          </el-form-item>
          <el-form-item label="连班加班" :label-width="formLabelWidth" prop="continuousshifthours">
            <el-input disabled v-model="attendanceResultReport.continuousshifthours" @change="numberChange"></el-input>
          </el-form-item>
          <el-form-item label="超时加班" :label-width="formLabelWidth" prop="overtime">
            <el-input disabled v-model="attendanceResultReport.overtime" @change="numberChange"></el-input>
          </el-form-item>
          <el-form-item label="总出勤" :label-width="formLabelWidth" prop="totalduration">
            <el-input v-model="attendanceResultReport.totalduration" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth" prop="totalduration">
            <el-input v-model="attendanceResultReport.summaryPeople" ></el-input>
          </el-form-item>

          <el-form-item style="text-align: right">
            <el-button @click="edit('attendance')" type="primary">确认</el-button>
            <el-button @click="drawer1=false">取消</el-button>
          </el-form-item>
        </el-form>

      </el-row>
    </el-drawer>

    <el-dialog
        top="15vh"
        :visible.sync="attendacneResultReportShow"
        width="50%"
        title="考勤数据"
        :before-close="handleClose"
        center>
      <el-upload
          class="upload-demo"
          drag
          :http-request="uploadAttendanceResultReport"
          auto-upload
          accept=".xlsx,.xls"
          multiple action="#" style="text-align: center!important;">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传1个.xls/.xlsx文件
          <p> 导入模板请先点击到处本页数据，再按模板整理数据导入</p>
        </div>
      </el-upload>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogFormVisible" append-to-body center>
      <div slot="title">
        <h3>提示</h3>
        <h5>上传文件中：
          <el-tag type="info" v-text="allNum"></el-tag>
          条数据，成功导入
          <el-tag type="success" v-text="successNum"></el-tag>
          条数据，失败导入：
          <el-tag type="danger" v-text="errorNum"></el-tag>
          条数据<span v-if="errorNum>0">，错误信息如下：</span></h5>
      </div>
      <el-row>
        <ol v-if="list.length>0" style="text-align: center;height:35vh;overflow-y: scroll;">
          <li v-for="(item,index) in list" style="text-align: left;">
            <span v-text="item" style="width: 350px;overflow: hidden;text-overflow: ellipsis"></span></li>
        </ol>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import ToolBar from "@/components/common/ToolBar";
import moment from "moment";

export default {
  name: "attendanceResultReport",
  components: {ToolBar},
  data() {
    var checkBasicAttendance = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('基本出勤时间不能为空'));
      }
      setTimeout(() => {
        if (value > 8) {
          callback(new Error('基本出勤时间不超过8小时...'));
        } else {
          callback();
        }

      }, 1000);
    };
    return {
      dialogVisible:false,
      // 数据核对结果
      errorData:[],
      attendanceResultReport: {},
      currentPage: 1,
      total: 0,
      size: 10,
      tableData: [],
      dingUsersListName: null,
      dingUsersList: [],
      userList: [],
      isDowload: false,
      attendacneResultReportShow:false,
      list: [],
      allNum: 0,
      successNum: 0,
      errorNum: 0,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      dialogFormVisible: false,
      getDataDialogFormVisible: false,
      sjhdDialogFormVisible: false,
      form: {
        start: moment().format("YYYY-MM-DD"),
        end: moment().format("YYYY-MM-DD"),
        userId: null,
        name: null,
        workDate: null,
        timeResult: null,
        checkType: null,
        archivesDate: new Date(),
        hiredDate: null,
        attendanceDate: new Date().getTime() - 3600 * 1000 * 24,
        dept:null,
        userIds:[],
        depts:[],
        groupNames:[]
      },
      sjhdForm:{
        attendanceDate: new Date().getTime() - 3600 * 1000 * 24,
        start: null,
        end: null,
        fileList: ''
      },
      formLabelWidth: '80px',
      timeResultList: [
        {
          label: "正常",
          value: "Normal",
        },
        {
          label: "早退",
          value: "Early",
        }, {
          label: "迟到",
          value: "Late",
        }, {
          label: "严重迟到",
          value: "SeriousLate",
        }, {
          label: "旷工迟到",
          value: "Absenteeism",
        }, {
          label: "未打卡",
          value: "NotSigned",
        },
      ],
      drawer: false,
      direction: 'rtl',
      attendanceResultList: [],
      popoverShow: false,
      row: {},
      attendanceDate: [moment().add("weeks",-1).format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")],
      approve: {},
      innerDrawer: false,
      drawer1: false,
      multipleSelection: [],
      isAdd: false,
      rules: {
        basicattendance: [
          {validator: checkBasicAttendance, trigger: "blur"}
        ]
      },
      deptList: [],
      groupList: []

    }
  },
  created() {
    this.attendanceDate= [moment().add("weeks",-1).format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")]
    this.sjhdForm.attendanceDate= [moment().add("weeks",-1).format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")]
    this.dateChange()
    this.getDataList()

  },
  mounted() {
    this.getDeptList()
  },
  methods: {
    dateChange() {
      this.form.start = this.attendanceDate[0]
      this.form.end = this.attendanceDate[1]
    },
    numberChange() {
      this.attendanceResultReport.totalduration =
          parseFloat(this.attendanceResultReport.basicattendance)
          + parseFloat(this.attendanceResultReport.basicovertime) + parseFloat(this.attendanceResultReport.continuousshifthours) + parseFloat(this.attendanceResultReport.overtime)
    },
    setAddDialogVisible() {
      this.drawer1 = true
      this.isAdd = true
      this.attendanceResultReport = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getApprove(item) {
      console.log("Item;", item)
      const id = item.procinstId + item.userId
      axios.get("/ding_approve_list/get/" + id).then(res => {
        if (res.data.success) {
          this.innerDrawer = true
          this.approve = res.data.data
          console.log("Approve:", res.data.data)
        } else {
          this.approve = null
        }
      })
    },
    getDeptList() {
      axios.get("/fin_user_roster/deptList").then(res => {
        if (res.data.success) {
          this.deptList = res.data.data
        } else {
          this.deptList = []
        }
      })
    },
    deptChange() {
      if (this.form.depts.length>0) {
        this.getGroupList()

      }

    },
    getGroupList() {
      let data={
        depts:this.form.depts
      }
      axios.post("/fin_user_roster/groupList",data).then(res => {
        if (res.data.success) {
          this.groupList = res.data.data
        } else {
          this.groupList = []
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.drawer1 = false
            this.attendanceResultReport = {}
            done();
          })
          .catch(_ => {
          });
    },
    tableRowClassName({row, rowIndex}) {
      if ((row.basicattendance < 8 || row.basicattendance === null) && row.week !== '七') {
        return 'error-row';
      }
      return '';
    },
    goGetData() {
      this.getDataDialogFormVisible = true
    },
    sjhd(){
      this.sjhdDialogFormVisible = true;
    },
    handleEdit(row) {
      this.attendanceResultReport = row
      this.drawer1 = true
      this.isAdd = false

    },
    edit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.attendanceResultReport.updateuserid = this.$store.state.userInfo.id
          axios.post("/attendance_result_report/update/" + this.$store.state.userInfo.id + "/" + this.$store.state.userInfo.name, this.attendanceResultReport).then(res => {
            if (res.data.success) {
              this.$tools.showMessage(res.data.message, "success")
              this.getDataList()
              this.drawer1 = false
              this.attendanceResultReport = {}
            } else {
              this.$tools.showMessage(res.data.message, "error")
            }
          })
        }
      })

    },
    handleDelete(index, row) {
      console.log(index, row);
      this.multipleSelection.push(row)
      this.$tools.showMessageBox("确认删除选择的：" + this.multipleSelection.length + "条考勤数据？", "操作确认", "warning").then(confirm => {
        axios.post("/attendance_result_report/deleteBatch" + this.$store.state.userInfo.id + "/" + this.$store.state.userInfo.name, this.multipleSelection).then(res => {
          if (res.data.success) {
            this.$tools.showMessage(res.data.message, "success")
            this.getDataList()
          } else {
            this.$tools.showMessage(res.data.message, "error")
          }
        })
      }).catch(cancel => {
        this.$tools.showMessage("操作取消！", "info")

      })
    },
    getDataList() {
      this.dialogFormVisible = false
      // this.form.start=this.attendanceDate[0]
      // this.form.end=this.attendanceDate[1]
      console.log("查询数据：", this.form)
      if(this.form.userIds===""){
        this.form.userIds=[]
      }
      axios.post("/attendance_result_report/list/" + this.currentPage + "/" + this.size, this.form).then(res => {
        console.log("打卡信息：", res)
        if (res.data.success) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.pages = res.data.data.pages
        } else {
          this.tableData = []
          this.total = 0
          this.pages = 1
        }

      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getDataList()
    },
    goSearch() {
      this.dialogFormVisible = true

    },
    reSet() {
      this.form = {
        start: null,
        end: null,
        userId: null,
        name: null,
        workDate: null,
        timeResult: null,
        checkType: null,
        attendanceDate: new Date().getTime() - 3600 * 1000 * 24
      }
      this.getDataList()
    },
    handleChange() {
      this.getDataList()
    },
    handleUserChange() {
      // this.form.userId=
      console.log('Form:', this.form)
    },
    deleteById() {
      console.log("用户扫描删除")
      this.$tools.showMessageBox("确认删除选择的：" + this.multipleSelection.length + "条考勤数据？", "操作确认", "warning").then(confirm => {
        axios.post("/attendance_result_report/deleteBatch" + this.$store.state.userInfo.id + "/" + this.$store.state.userInfo.name, this.multipleSelection).then(res => {
          if (res.data.success) {
            this.$tools.showMessage(res.data.message, "success")
            this.getDataList()
          } else {
            this.$tools.showMessage(res.data.message, "error")
          }
        })
      }).catch(cancel => {
        this.$tools.showMessage("操作取消！", "info")
      })
    },
    updateById() {
      console.log("用户扫描修改")

      this.handleEdit(this.multipleSelection[0])
    },
    getDataFromDingDing() {
      this.form.start = moment(this.attendanceDate[0]).format("YYYY-MM-DD")
      this.form.end = moment(this.attendanceDate[1]).format("YYYY-MM-DD")
      console.log("查询数据：", this.form)
      this.$tools.openLoading()
      axios.post("/attendance_result_report/get", this.form).then(res => {
        if (res.data.success) {
          this.handleCurrentChange(1)
          this.$tools.closeLoading();
          this.getDataDialogFormVisible = false;
        }
      })
    },
    sjhdReport(res) {
      this.sjhdForm.start = moment(this.sjhdForm.attendanceDate[0]).format("YYYY-MM-DD")
      this.sjhdForm.end = moment(this.sjhdForm.attendanceDate[1]).format("YYYY-MM-DD")
      this.$refs.sjhdForm.validate(valid=>{
        if(!valid){
          this.$tools.showMessage("请完善表单信息...", 'warning')
          this.sjhdDialogFormVisible = true;
          return
        }
        let formData = new FormData();
        formData.append("file", res.file)
        formData.append("start", this.sjhdForm.start)
        formData.append("end", this.sjhdForm.end)
        this.$tools.openLoading()
        axios({
          method: "POST",
          url: "/attendance_result_report/upload",
          headers: {
            'content-type': 'multipart/form-data',
          },
          data: formData
        }).then(res => {
          this.$tools.closeLoading();
          if(res.data.success){
              this.errorData = res.data.data;
              console.log(this.errorData);
          }
        }).catch(err=>{
          this.$tools.closeLoading();
        })
      })
    },
    handleChangeUpload(file,fileList){
      this.sjhdForm.fileList = URL.createObjectURL(file.raw);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.sjhdForm.fileList = '';
    },
    handlePreview(file) {
      console.log(file);
    },
    getDingAttendanceDetail(row) {
      console.log("Row:", row)
      this.row = row
      const data = {
        workDate: row.attendancedate,
        userId: row.userid
      }
      axios.post("/ding_attendance_result/getDetail", data).then(res => {
        console.log("Res:", res)
        if (res.data.success) {
          this.attendanceResultList = res.data.data
        } else {
          this.attendanceResultList = []
        }
      })
      this.drawer = true
    },
    exportData( all ) {
      if(!all){
        // 导出当前页
        this.form.page = this.currentPage;
        this.form.limit = this.size;
      }else {
        this.form.page = null;
        this.form.limit = null;
      }
      axios({
        method: 'post',
        url: '/excel/attendanceResultReport', // 后端接口地址
        responseType: 'blob', // 表明返回数据是二进制文件
        data: this.form
      }).then(response => {
        let filename = '四川瀚海' + moment(this.form.start).format('YYYY年MM月DD日')+'至'+moment(this.form.end).format('YYYY年MM月DD日') + (!this.form.dept ? '' : this.form.dept) + (!this.form.groupName ? '' : this.form.groupName) + '考勤信息.xlsx';
        fdCommon.down(filename,response.data)
      }).catch(error => {
        console.error('导出 Excel 失败:', error);
      });
    },
    addBatchData()
    {
      console.log("批量添加")
      this.attendacneResultReportShow = true
    }
    ,
    uploadAttendanceResultReport(res)
    {
      console.log(res)
      let formData = new FormData();
      formData.append("file", res.file)
      axios({
        method: "POST",
        url: "/attendance_result_report/addBatch/" + this.$store.state.userInfo.id + "/" + this.$store.state.userInfo.name,
        headers: {
          'content-type': 'multipart/form-data',
        },
        data: formData
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          let successNum = parseInt(res.data.data.successNum);
          let errorNum = parseInt(res.data.data.errorNum);
          let allNum = successNum + errorNum
          if (errorNum > 0) {
            let list = res.data.data.list
            this.successNum = successNum;
            this.errorNum = errorNum
            this.allNum = allNum;
            this.list = list
            this.dialogVisible = true
          } else {
            this.attendacneResultReportShow = false
            this.getDataList()
            this.$message({
              dangerouslyUseHTMLString: true,
              message: "成功上传<b>" + allNum + "</b>条数据",
              type: "success"
            })
          }
        } else {
          this.$message({
            dangerouslyUseHTMLString: true,
            message: res.data.message,
            type: "error"
          })
        }
      })
    }

  },

}
</script>

<style scoped lang="less">
.attendance_result_report {
  .select {
    //margin-bottom: 0.1rem;
    display: inline-flex !important;
  }

  .el-input--suffix .el-input__inner {
    padding-right: 0;
  }
}

</style>
